package com.me {
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.filesystem.File;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	
	import mx.controls.Alert;

	/**
	 *
	 * @author yw
	 *
	 * @Date 2011-9-16 下午03:11:56
	 */
	public class FileLoader {
		private static var _instance:FileLoader;

		private var _applicatioDomain:ApplicationDomain;

		private var _loadedCallBack:Function;

		public function FileLoader(enforce:SingletonEnfroce) {
			if (enforce == null) {
				throw new Error("FileLoader can not be instance");
			}
		}

		public static function getInstance():FileLoader {
			if (_instance == null) {
				_instance = new FileLoader(new SingletonEnfroce());
			}
			return _instance;
		}

		public function loadFile(file:File, loaded:Function):void {
			if (loaded == null || file == null || !file.exists) {
				return;
			}

			_loadedCallBack = loaded;

			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			loader.load(new URLRequest(file.nativePath));
		}

		public function getClassByName(na:String):Object {
			return _applicatioDomain.getDefinition(na);
		}

		private function ioErrorHandler(e:IOErrorEvent):void {
			Alert(e.text);
		}

		private function loadComplete(e:Event):void {
			var targetInfo:LoaderInfo = e.currentTarget as LoaderInfo;
			var url:String = e.currentTarget.url;
			e.currentTarget.removeEventListener(Event.COMPLETE, loadComplete);

			var tempLoader:Loader = new Loader();
			var loaderContext:LoaderContext = new LoaderContext();
			loaderContext.allowCodeImport = true;
			tempLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadedHandle);
			tempLoader.loadBytes(targetInfo.bytes, loaderContext);
		}

		private function onLoadedHandle(event:Event):void {
			event.currentTarget.removeEventListener(Event.COMPLETE, loadComplete);
			_applicatioDomain = event.currentTarget.applicationDomain;
			_loadedCallBack(event.currentTarget.content);
		}
	}
}

class SingletonEnfroce {

}
